package com.zl.utils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

/**
 * User: c3t
 * Date: 13-12-10
 * Time: 上午10:54
 */
public class JsonUtil {
	private static ObjectMapper mapper = new ObjectMapper();
	private  static JsonUtil jsonUtil = new JsonUtil();

	private JsonUtil() {

	}

	public static JsonUtil getInstance() {
		return jsonUtil;
	}

	public static ObjectMapper getMapperInstance() {
		return mapper;
	}

	public static JsonFactory getJsonFactory(){
		return new JsonFactory();
	}

	public String obj2Json(Object obj){
		StringWriter stringWriter = new StringWriter();
		try {
			JsonGenerator jsonGenerator = getJsonFactory().createGenerator(stringWriter);
			mapper.writeValue(jsonGenerator, obj);
			return stringWriter.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object json2Obj(String json,Class<?> clz){
		try {
			return mapper.readValue(json,clz);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
